package com.bhs.sansonglogistics.ui.order;

import static com.amap.api.services.route.RouteSearch.DRIVING_SINGLE_DEFAULT;
import static com.bhs.sansonglogistics.bean.Location.companyLat;
import static com.bhs.sansonglogistics.bean.Location.companyLon;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.bean.SourceGoodsDetailsBean;
import com.bhs.sansonglogistics.net.map.DrivingRouteOverLay;
import com.bhs.sansonglogistics.utils.GetDistanceUtils;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

/**
 * 订单路线规划
 */
public class MapNavigation implements AMap.OnMyLocationChangeListener, PoiSearch.OnPoiSearchListener, RouteSearch.OnRouteSearchListener {


    //初始化地图控制器对象
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private Context mContext;
    private RouteSearch routeSearch;
    private Marker endMarker;
    private Marker startMarker;
    private double distance;
    private SourceGoodsDetailsBean.DataDTO.OrderInfoDTO order_info;

    public MapNavigation(Context mContext) {

        this.mContext = mContext;

    }

    public void initView(MapView mMapView) {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类

        //myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_che));
        //连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。
        // （1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。 只定位一次
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.interval(2000);
        //设置定位蓝点的Style
        aMap.setMyLocationStyle(myLocationStyle);
        //设置默认定位按钮是否显示，非必需设置。
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
       // aMap.setMyLocationEnabled(true);
        aMap.setOnMyLocationChangeListener(this);
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setMyLocationButtonEnabled(false); //显示默认的定位按钮
        //设置希望展示的地图缩放级别
        aMap.animateCamera(CameraUpdateFactory.zoomTo(17));

        try {
            routeSearch = new RouteSearch(mContext);
        } catch (AMapException e) {
            throw new RuntimeException(e);
        }
        routeSearch.setRouteSearchListener(this);
    }


    private LatLng startLatLng;
    private LatLng endLatLng;

    private String endContent;
    private String startContent;

    private boolean isNeedCar;//是否需要画车

    public void setToLocation(SourceGoodsDetailsBean.DataDTO dataDTO) {
        aMap.clear();// 清理地图上的所有覆盖物
        order_info = dataDTO.getOrder_info();
        double startLatitude = 0;
        double startLongitude = 0;
        double endLatitude = 0;
        double endLongitude = 0;
        if (order_info.getStatus() == 5) {
            //货主自送
            if (order_info.getJiaohuo_type() == 1) {
                startContent = "等待发货人自送";
                startLatitude = Double.parseDouble(order_info.getPickup_latitude());
                startLongitude = Double.parseDouble(order_info.getPickup_longitude());
                endLatitude = companyLat;
                endLongitude = companyLon;
                //头像
                startLatLng = new LatLng(startLatitude, startLongitude);
                endLatLng = new LatLng(endLatitude, endLongitude);

            } else {
                //物流自提
                endLatitude = Double.parseDouble(order_info.getPickup_latitude());
                endLongitude = Double.parseDouble(order_info.getPickup_longitude());
                startLatitude = companyLat;
                startLongitude = companyLon;
                //距离
                distance = GetDistanceUtils.getDistance(startLongitude,
                        startLatitude, endLongitude, endLatitude);
                endContent = String.format("距物流%s公里", distance);
                //头像
                startLatLng = new LatLng(endLatitude, endLongitude);
                endLatLng = new LatLng(startLatitude, startLongitude);
            }
        } else if (order_info.getStatus() == 7) {
            endContent = "已入库等待发车";
            startLatitude = companyLat;
            startLongitude = companyLon;
            endLatLng = new LatLng(startLatitude, startLongitude);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(endLatLng,17));
        } else if (order_info.getStatus() == 9) {
            isNeedCar = true;
            startLatitude = companyLat;
            startLongitude = companyLon;
            endLatitude = Double.parseDouble(dataDTO.getWaybill_info().getOutlets_latitude());
            endLongitude = Double.parseDouble(dataDTO.getWaybill_info().getOutlets_longitude());
            //头像
            endLatLng = new LatLng(startLatitude, startLongitude);
            startLatLng = new LatLng(endLatitude, endLongitude);
            endContent = String.format("发货网点:%s", order_info.getPickup_city());
            //距离
            distance = GetDistanceUtils.getDistance(startLongitude,
                    startLatitude, endLongitude, endLatitude);

            startContent = String.format("收货网点:%s", dataDTO.getWaybill_info().getOutlets_city());
        } else if (order_info.getStatus() == 11) {
            //送货上门
            if (order_info.getPeisong_type() == 1) {
                startLatitude = Double.parseDouble(dataDTO.getWaybill_info().getOutlets_latitude());
                startLongitude = Double.parseDouble(dataDTO.getWaybill_info().getOutlets_longitude());
                endLatitude = Double.parseDouble(order_info.getReceive_latitude());
                endLongitude = Double.parseDouble(order_info.getReceive_longitude());
                //头像
                startLatLng = new LatLng(startLatitude, startLongitude);
                endLatLng = new LatLng(endLatitude, endLongitude);
                //距离
                distance = GetDistanceUtils.getDistance(startLongitude,
                        startLatitude, endLongitude, endLatitude);
                startContent = String.format("等待派送，距%s公里", distance);
            } else {
                //收货人自提
                endLatitude = Double.parseDouble(dataDTO.getWaybill_info().getOutlets_latitude());
                endLongitude = Double.parseDouble(dataDTO.getWaybill_info().getOutlets_longitude());
                startLatitude = Double.parseDouble(order_info.getReceive_latitude());
                startLongitude = Double.parseDouble(order_info.getReceive_longitude());
                //距离
                distance = GetDistanceUtils.getDistance(startLongitude,
                        startLatitude, endLongitude, endLatitude);
                endContent = "待收货人取货";
                //头像
                startLatLng = new LatLng(startLatitude, startLongitude);
                endLatLng = new LatLng(endLatitude, endLongitude);
            }
        } else if (order_info.getStatus() == 15 || order_info.getStatus() == 20) {
            startLatitude = Double.parseDouble(order_info.getPickup_latitude());
            startLongitude = Double.parseDouble(order_info.getPickup_longitude());
            endLatitude = Double.parseDouble(order_info.getReceive_latitude());
            endLongitude = Double.parseDouble(order_info.getReceive_longitude());

            startLatLng = new LatLng(endLatitude, endLongitude);
            endLatLng = new LatLng(startLatitude, startLongitude);
            startContent = "已签收";
        }

        if (startLatitude == 0 && endLatitude == 0) {
            return;
        }
        //Marker
        addStartAndEndMarker(dataDTO);
        if (startLatitude == 0 || endLatitude == 0) {
            return;
        }
        //路线
        LatLonPoint ADot = new LatLonPoint(startLatitude, startLongitude);
        LatLonPoint BDot = new LatLonPoint(endLatitude, endLongitude);

        RouteSearch.FromAndTo fromTo = new RouteSearch.FromAndTo(ADot, BDot);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromTo, DRIVING_SINGLE_DEFAULT, null, null, "");
        routeSearch.calculateDriveRouteAsyn(query);


    }

    private DriveRouteResult mDriveRouteResult;

    //当前位置经纬度
    @Override
    public void onMyLocationChange(Location location) {
//        location.getLongitude();
//        location.getLatitude();

    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onBusRouteSearched(BusRouteResult result, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int i) {
        if (result.getPaths().size() > 0) {
            mDriveRouteResult = result;
            final DrivePath drivePath = mDriveRouteResult.getPaths()
                    .get(0);
            if (isNeedCar) {
                int vehicle = drivePath.getPolyline().size() / 2;
                LogUtils.d(drivePath.getPolyline().size() + "===" + drivePath.getSteps().size());
                LatLng vehicleLatLng = new LatLng(drivePath.getPolyline().get(vehicle).getLatitude()
                        , drivePath.getPolyline().get(vehicle).getLongitude());

                vehicleMarker(vehicleLatLng);
            }



            DrivingRouteOverLay drivingRouteOverlay = new DrivingRouteOverLay(
                    mContext, aMap, drivePath,
                    mDriveRouteResult.getStartPos(),
                    mDriveRouteResult.getTargetPos(), null);
            drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
            drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
            drivingRouteOverlay.removeFromMap();
            drivingRouteOverlay.addToMap();
            drivingRouteOverlay.zoomToSpan();
        }
    }

    private void vehicleMarker(LatLng vehicleLatLng) {
        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.custom_info_window2, null);
        TextView tv_content = infoWindow.findViewById(R.id.tv_content);
        TextView tv_predict = infoWindow.findViewById(R.id.tv_predict);
        tv_predict.setText(String.format("预计%s~%s天到达", order_info.getTransport_day_min(), order_info.getTransport_day_max()));
        tv_content.setText(String.format("距收货网点%skm", distance));
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(infoWindow);
        aMap.addMarker((new MarkerOptions())
                .position(vehicleLatLng).icon(bitmap));
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    public void addStartAndEndMarker(SourceGoodsDetailsBean.DataDTO dataDTO) {

        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.custom_info_window, null);
        TextView tv_content = infoWindow.findViewById(R.id.tv_content);
        if (!TextUtils.isEmpty(startContent)) {
            tv_content.setText(startContent);
        } else {
            tv_content.setVisibility(View.GONE);
        }
        if(order_info.getStatus() == 9||order_info.getStatus() == 11){
            ImageView imageView = infoWindow.findViewById(R.id.iv_logo);
            imageView.setImageResource(R.mipmap.ic_blogistics);
        }
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(infoWindow);
        startMarker = aMap.addMarker((new MarkerOptions())
                .position(startLatLng).icon(bitmap));


        if (order_info.getStatus() == 11) {
            View infoWindow2 = LayoutInflater.from(mContext).inflate(R.layout.custom_info_window, null);
            TextView tv_content2 = infoWindow2.findViewById(R.id.tv_content);
            if (!TextUtils.isEmpty(endContent)) {
                tv_content2.setText(endContent);
            } else {
                tv_content2.setVisibility(View.GONE);
            }

            BitmapDescriptor bitmap2 = BitmapDescriptorFactory.fromView(infoWindow2);
            endMarker = aMap.addMarker((new MarkerOptions())
                    .position(endLatLng).icon(bitmap2));
        } else {
            String company_pic;
            if (order_info.getStatus() == 15 || order_info.getStatus() == 20) {
                company_pic = dataDTO.getCargo_info().getHeaderpic();
            } else {
                company_pic = SharedPreferencesUtils.getString(mContext, "company_pic");
            }
            Glide.with(mContext).load(company_pic).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                    View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.custom_info_window, null);
                    ImageView imageView = infoWindow.findViewById(R.id.iv_logo);
                    TextView tv_content = infoWindow.findViewById(R.id.tv_content);
                    if (!TextUtils.isEmpty(endContent)) {
                        tv_content.setText(endContent);
                    } else {
                        tv_content.setVisibility(View.GONE);
                    }
                    imageView.setImageDrawable(resource);
                    BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(infoWindow);
                    endMarker = aMap.addMarker((new MarkerOptions())
                            .position(endLatLng).icon(bitmap));
                }
            });
        }

    }

}
